/**
 * 分类列表 页面渲染 下拉加载页面
 *
 */
require(['jquery','../modules/pageSize','../modules/popup'],function($, pageSetSize, popup){
	setRootFontSize(pageSetSize);
    // 获取参数
    var page =1;
    var category_id,
        _sort,
        _select,
        menuId;
    /*初始化*/
    var counter = 0; /*计数器*/
    var pageStart = 0; /*offset*/
    var pageSize = 10; /*size*/
    var isEnd = false;/*结束标志*/
    var isAjax = false;/*防止滚动过快，服务端没来得及响应造成多次请求*/
	var _ycMarkArr = ["闪购", "促销", "套餐"];
    // 首次加载
    getData(pageStart,pageSize,page,category_id,_sort,_select);
    menuOperate();
    /*监听加载更多*/
    $(window).scroll(function(){
        /*滚动加载时如果已经没有更多的数据了、正在发生请求时，不能继续进行*/
        if(isEnd == true || isAjax == true){
            return;
        }
        // 当滚动到最底部以上100像素时， 加载新内容
        if ($(document).height() - $(this).scrollTop() - $(this).height()<100){
            counter ++;
            pageStart = counter * pageSize;
            getData(pageStart, pageSize,(counter+page),category_id,_sort,_select);
        }
    });
    // 菜单操作
    function menuOperate(){
        // 二级分类效果
        var de_curr;
        $('.sort-bar li').on('click',function(){
            var curr =$('.sort-bar li').index(this);
            de_curr = curr;
            $(this).addClass('active').siblings().removeClass('active');
            $('.tips').hide();
            $('.tips').eq(curr).show();
            $('body').append('<div class="pop-mask"></div>');
            var str = $('.pop-mask');
            str.hide();
            str.eq(0).show();
        });
        $('.tips').on('click','a',function(){
            $(this).addClass('active').siblings().removeClass('active');
            $(this).parent().hide();
            $('.sort-bar li').eq(de_curr).find('a').remove();
            category_id = $(this).attr("category-id");
            _sort = $(this).attr("sort");
            _select = $(this).attr("select");
            var html = '<a href="javascript:void(0);">'+$(this).text()+'</a>';
            $('.sort-bar li').eq(de_curr).html(html);
            $('.pop-mask').remove();
            isEnd =false;
            counter = 0;
            $('.filter-goods-list ul div.text').remove();
            getData(pageStart,pageSize,page,category_id,_sort,_select)
        });

    }

    function getData(offset,size,page,category_id,_sort,_select){
        if(_cat_id){
            if(_sort == undefined && _select == undefined ){
                menuId =category_id;
            }
            if(category_id == undefined && _select == undefined ){
                menuId =+_cat_id+'/sort/'+_sort;
            }
            if(category_id == undefined && _sort == undefined ){
                menuId =+_cat_id+'/select/'+_select;
            }
            if(category_id == undefined  && _sort == undefined && _select == undefined){
                menuId =_cat_id;
            }
            if(category_id == ''  && _sort == undefined && _select == undefined){
                menuId =_cat_id;
            }
			if(isEnd){
				popup.alertPopup("没有更多数据！");	
			}
			if(isAjax) return;
			
			popup.loadPopup("正在加载中..."); 
            isAjax = true;
            $.ajax({
                url:'/home/GoodsList/ajax/category_id/'+menuId+getFixedExtraUrl(),
                type:'GET',
                data:{p:page},
                dataType:'json',
                success:function(data){
					popup.removeLoad();
					isAjax = false;
                    var listData = data.data;
                    if(listData == null || listData == 0 ){
                        if(data.count == 0 ){
                            $('.filter-goods-list ul').html('');
                            $(".empty-box").show();                            
                        }
                    }
                    if(listData){
                        $(".empty-box").hide();
                        var menuData = data.store_cat_msg;
                        var  sum = listData.length,
                            page_current = data.page,
                            totalPage = data.totalPage;
                        var result = '',
                            menuHtml = '';

                        /************业务逻辑块：实现拼接html内容并append到页面*****************/

                        if(sum - offset < size ){
                            size = sum - offset;
                        }
                        /*使用for循环模拟SQL里的limit(offset,size)*/
                        if(menuData != undefined && category_id == undefined && _sort == undefined  && _select == undefined && page_current ==1 ){
                            for(var i= 0 ; i<menuData.length; i++){
                                menuHtml+= '<a category-id="'+menuData[i].store_cat_id+'" href="javascript:void(0)">'+menuData[i].cat_name+'</a>'
                            }
                            $('.full-select-category').append(menuHtml);
                        }
						var cdata = null;
                        for(var j= 0; j < listData.length; j++){
							cdata = listData[j];
                            if(cdata.spec_info == null){
                                cdata.spec_info = '';
                            }
                            var store_cur = cdata.store, store_last = cdata.freez;
                            var store_out = parseInt(store_cur - store_last);
							// 0: 闪购 1：促销 2：组合促销
							var g_mark = -1;
							var g_price = "";
							var _link = '/Home/goods/detail/id/'+cdata.store_pid+'/local_id/'+cdata.local_id+'/top_local_id/'+yc_pass_arr.top_local_id;
							if(!!cdata.flashPrice){
								g_mark = 0;
								g_price = cdata.flashPrice;								
							}else if(!!cdata.proPrice){
								g_mark = 1;
								g_price = cdata.proPrice;									
							}else if(cdata.groupPromotion){
								g_mark = 2;
							}
                            result += '<li>';
                            result += '<a href="'+_link+'" class="img '+(store_out > 0 ? "" : "sold_out")+'"><img src="'+getDefaultImg(cdata.image)+'"></a>';
                            result += '<a href="'+_link+'" class="name text-hide">' + (g_mark == -1 ? "" : ('<i class="o-mark">'+_ycMarkArr[g_mark]+'</i>')) + cdata.name + '</a>';
                            result += '<p class="des text-hide">'+cdata.spec_info+'</p>';
							if(g_mark == 0){
								result += '<p class="price"><span class="sale-price">￥'+g_price+'</span></p>';
							}else if(g_mark == 1 && parseFloat(g_price) != parseFloat(cdata.price)){
								result += '<p class="price"><span class="sale-price">￥'+g_price+'</span><span class="old-price">￥'+cdata.price+'</span></p>';
							}else {
								result += '<p class="price"><span class="sale-price">￥'+cdata.price+'</span></p>';
							}
							result += '<a href="javascript:void(0);" class="cart" onclick="addIntoCart(event,this)" data-sid ="'+cdata.local_id+'" data-pid ="'+cdata.product_id+'" data-gid ="'+cdata.goods_id+'" data-spid ="'+cdata.store_pid+'" >+<label>+1</label></a>';
                             result += '</li>';
                        }
                        if(category_id == undefined && _sort == undefined && _select == undefined){
                            $('.filter-goods-list ul').append(result);
                        }
                        else {
                            if(parseInt(page_current)>1){
                                $('.filter-goods-list ul').append(result);
                            }else{
                                $('.filter-goods-list ul').html(result);
                            }
                        }
                        if ( parseInt(page_current)  >= totalPage){
                            isEnd = true;
                        }
                    }
                },
                error:function(){
					popup.removeLoad();
                    popup.alertPopup('服务器异常,请稍后重试！');
                }
            });
        }
    }
});